<template type="">
  <div class="container">
    <div class="app-container">
      <el-tree default-expand-all :data="depts" :props="defaultProps" :expand-on-click-node="false">
        <!-- 节点结构 -->
        <!-- v-slot="{ node, data }" 只能作用在template -->
        <template #default="{ data }">
          <el-row :style="{ width: '100%' }" type="flex" justify="space-between">
            <div>{{ data.name }}</div>
            <el-row style="width: 200px;" type="flex" justify="space-between">
              <span>{{ data.managerName }}</span>
              <el-dropdown @command="onOperation($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </el-row></template>
      </el-tree>

    </div>
    <AddDep ref="addDept" v-model="visiable" :current-node-id="currentNodeId" @updateDepartment="loadData" />
  </div>
</template>
<script>
import { getDepartmentsAPI, delDepartmentAPI } from '@/api/department'
import { buildTree } from '@/utils'
import AddDep from './AddDep.vue'
import { Message } from 'element-ui'

export default {
  name: 'Department',
  components: {
    AddDep
  },
  data() {
    return {
      depts: [],
      currentNodeId: null,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      visiable: false
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    async loadData() {
      const res = await getDepartmentsAPI()
      const tree = buildTree(res)
      this.depts = tree
    },
    onOperation(operation, id) {
      if (operation === 'add') {
        // 添加子部门
        this.visiable = true
        this.currentNodeId = id
      } else if (operation === 'edit') {
        // 编辑部门
        this.visiable = true
        this.currentNodeId = id
        this.$nextTick(() => {
          this.$refs.addDept.getDepartmentDetail()
        })
      } else if (operation === 'del') {
        // 删除
        this.$confirm('您确认要删除该部门吗').then(async() => {
          await delDepartmentAPI(id)
          // 提示消息
          Message.success('删除部门成功')
          this.loadData()
        })
      }
    }
  }
}
</script>

<style scoped>
.container {
  padding: 30px 140px;
  font-size: 14px;
  background-color: #fff;
  margin: 20px;
}
</style>
